<template>
  <div class="app-container calendar-list-container">

    <!-- 查询-->
    <el-card>
      <div class="block">
        <span style="color:gray; font-size:16px"> 时间范围: </span>

        <el-date-picker v-model="transactionQuery.timeInterval" type="datetimerange" :picker-options="pickerOptions" :default-time="['00:00:00', '00:00:00']" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="right">
        </el-date-picker>
      </div>
      <div style="margin-bottom: 10px"></div>

      <el-select size="mini" clearable v-model="transactionQuery.modeId" placeholder="支付渠道">
        <el-option v-for="pay in payData" :key="pay.id" :label="pay.modeName" :value="pay.id">
        </el-option>
      </el-select>
      <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="支付流水" v-model="transactionQuery.outTradeNo">
      </el-input>
      <!-- <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="交易状态" v-model="transactionQuery.tradeStatus">
      </el-input> -->
      <div style="margin-bottom: 10px"></div>

      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="getList(1)" v-perm="'b:ab:search'">搜索</el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" v-perm="'b:ab:download'">导出</el-button>
    </el-card>
    <div style="margin-bottom: 10px"></div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading.body="listLoading" id="transactionTable" element-loading-text="加载中" border fit highlight-current-row :default-sort="{prop: 'createDate', order: 'descending'}">

      <el-table-column align="center" min-width="100" label="应用" prop="channelName">
      </el-table-column>

      <el-table-column align="center" label="支付方式" prop="modeName">
      </el-table-column>

      <el-table-column align="center" label="流水号" prop="outTradeNo">
      </el-table-column>
      <el-table-column align="center" label="渠道" prop="channelId" :hidden=true>
      </el-table-column>
      <el-table-column align="center" label="订单号" prop="tradeNo">
      </el-table-column>
      <el-table-column align="center" label="交易类型" prop="tradeType" :formatter="formatRole">
      </el-table-column>
      <el-table-column label="金额" align="center">
        <el-table-column align="center" label="平台" prop="platformFee">
        </el-table-column>
        <el-table-column align="center" label="机构" prop="orgFee">
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="异常类型" prop="type">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.platformFee > scope.row.orgFee">
            长款
          </el-tag>
          <el-tag type="danger" v-else-if="scope.row.platformFee < scope.row.orgFee">
            短款
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="交易时间" :formatter="dateFormat" prop="createDate">
      </el-table-column>
      <el-table-column align="center" label="处理状态" prop="status" :formatter="formatStatus" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status === 1">
            未处理
          </el-tag>
          <el-tag type="success" v-else-if="scope.row.status === 2">
            已处理
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作员姓名" prop="operatorName">
      </el-table-column>
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" size="mini">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-button type="danger" size="mini" plain @click="handleRefund(scope.row)" v-if="scope.row.recType==1 && scope.row.status==1">退 款</el-button>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="tablePage.page" :page-sizes="[10,20,30,50]" :page-size="tablePage.size" layout="total, sizes, prev, pager, next, jumper" :total="tablePage.total">
      </el-pagination>
    </div>

  </div>
</template>


<script>
import { mapGetters } from 'vuex'
import { queryAbnormalOrderDetail, refund } from '@/api/ordermanager'
import { pageParamNames } from '@/utils/constants'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import optionApi from '@/api/option'
export default {
  name: 'Transaction',
  data() {
    return {
      payData: [],
      payMap: new Map(),
      list: null,
      allStatistical: {
        transactionNumber: undefined,
        allTotalFee: undefined,
        allRefundTotalFee: undefined
      }, // 统计所有的数据
      listLoading: false,
      transactionQuery: {
        timeInterval: [
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000 * 2,
          new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000)
        ],
        orgId: this.orgId,
        modeId: undefined, // 支付渠道
        outTradeNo: undefined // 支付流水
      },
      tablePage: {
        current: null,
        pages: null,
        size: null,
        total: null
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '前天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['orgId', 'name', 'nick', 'avatar', 'roles', 'perms'])
  },
  created() {
    this.getList()
    this.initData()
  },
  methods: {
    formatRole: function(row, column) {
      return row.recType === 1 ? '消费' : row.recType === 2 ? '退款' : '未知'
    },
    formatStatus: function(row, column) {
      return row.status === 1 ? '未处理' : row.status === 2 ? '已处理' : '未知'
    },
    dateFormat: function(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return date.replace('T', ' ').substr(0, 19)
    },

    getList(current) {
      if (current) {
        this.tablePage.current = current
      }
      this.listLoading = true
      queryAbnormalOrderDetail(this.transactionQuery, this.tablePage).then(res => {
        this.list = res.data.page.records
        this.listLoading = false
        pageParamNames.forEach(name => this.$set(this.tablePage, name, res.data.page[name]))
      })
    },
    handleSizeChange(val) {
      this.tablePage.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.tablePage.current = val
      this.getList()
    },
    handleDownload() {
      this.listLoading = true
      var wb = XLSX.utils.table_to_book(document.querySelector('#transactionTable'))
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '交易明细.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      this.listLoading = false
      return wbout
    },
    handleRefund(row) {
      // console.log(row)
      var refundParam = {
        id: row.id,
        orgId: row.orgId,
        channelId: row.channelId,
        modeId: row.modeId,
        outTradeNo: row.outTradeNo,
        refundFee: row.platformFee
      }
      this.$confirm('是否确认退款?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          refund(refundParam)
            .then(res => {
              // console.log(res.data.data)
              this.$message({
                type: 'success',
                message: res.data.data
              })
              this.getList()
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '退款失败!'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '退款取消'
          })
        })
    },
    initData() {
      optionApi.show().then(res => {
        res.data.payOptions.forEach(obj => {
          this.payData.push(obj)

          this.payMap.set(obj.id, obj.modeName)
        })
      })
    }
  }
}
</script>
